home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Language/OS - Multiplatform Resource Library
/
LANGUAGE OS.iso
/
cpp_libs
/
answrbok
/
8_3.lha
/
8_3
/
8_3_date.c
next >
Wrap
C/C++ Source or Header
|
1993-08-08
|
2KB
|
100 lines
* Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
* The C++ Answer Book */
* Tony Hansen */
* All rights reserved. */
/ Exercise 8.3
/ Read in a date, with error checking
include <stream.h>
include <errno.h>
include <stdlib.h>
include <date.h>
/ return the maximum # of days
/ in a given year and month
nt maxday(long year, long month)
// check for february and leap years
if (month == 2)
if ((year % 4 == 0) &&
((year % 100 != 0) || (year % 400 == 0)))
return 29;
else
return 28;
// the rest are constant
static int numdays[] =
{
31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31
};
return numdays[month-1];
nt read_date(ostream &out, istream &in, date *val)
// set up flushing of the output stream
ostream *old = in.tie(&out);
// loop until we get something right
for ( ; ; out << "Try again\n")
{
// read a year number
out << "Type a year: ";
char buf[256], c;
if (!cin.get(buf, 256))
{
in.tie(old);
return 0;
}
in.get(c);
// check the integer
char *p;
errno = 0;
long year = strtol(buf, &p, 10);
if (*p || (p == buf) || errno)
continue;
// read a month number
out << "Type a month (a number from 1 - 12): ";
if (!cin.get(buf, 256))
{
in.tie(old);
return 0;
}
in.get(c);
// check the integer
errno = 0;
long month = strtol(buf, &p, 10);
if (*p || (p == buf) || errno ||
(month < 1) || (month > 12))
continue;
// read a day of the month
int maxd = maxday(year, month);
out << "Type a day (a number from 1 - " <<
maxd << "): ";
if (!cin.get(buf, 256))
{
in.tie(old);
return 0;
}
in.get(c);
// check the integer
errno = 0;
long day = strtol(buf, &p, 10);
if (*p || (p == buf) || errno ||
(day < 1) || (day > maxd))
continue;
// return the value, restoring the old tie first
in.tie(old);
val->set((int)month, (int)day, (int)year);
return 1;
}